<?php

namespace App\Http\Controllers\Api\V1\User;

use App\Models\Orders\Order;
use App\Models\RewardLog;
use App\Models\User\UserAddress;
use App\Models\User\Users;
use App\Models\Vuls\Vuls;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\V1\BaseController;
use App\Http\Controllers\Api\V1\TransformerController;
use App\Http\Controllers\Api\V1\CustomFommat;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class UserController extends BaseController
{

    /**
     * 获取sso登陆地址
     * @param mixed $request
     * @return string
     */
    public function getSsoLoginAddress (Request $request) {
        return $this->returnArray(['url' => env('SSO_HOST') . 'sso-login.do?appId=' . env('SSO_APPID')]);
    }

    /**
     * 获取回话id
     *
     * @return int
     */
    public function getSessionId () {

        if (\Auth::user()) {

            return \Auth::user()->id;
        }
        return 0;
    }

    /**
     * 获取用户基本信息数据
     * @param $id
     * @return mixed
     */
    protected function show ($id) {
        $user = new Users();
        $info = $user->getBaseInfo($id);

        if (!$info) {
            return $this->response->errorNotFound('user not found');
        }

        return $this->returnArray($info->toArray());
    }

    /**
     * 获取当前会话基础信息
     *
     * @return mixed
     */
    public function getUser (Request $request) {
        $userId = $this->getSessionId();
        return $this->show($userId);
    }

    /**
     * 用户注册
     * @param mixed $request
     * @return mixed
     */
    public function register (Request $request) {
    }

    /**
     * 用户更新
     * @param mixed $request
     * @return mixed
     */
    public function update (Request $request) {
        $user = new Users();
        //验证
        $validate = Validator::make($request->all(), [
            'alias' => ['required',Rule::unique('user_ext')->ignore($request->id,'user_id')]
        ],[
            'alias.required' => '昵称不能为空',
            'alias.unique' => '昵称已存在'
        ]);
        if($validate->fails()){
            $warnings = $validate->messages();
            return $this->returnValidate($warnings->first());
        }else{
            //头像上传非必须
            if ($request->file('avatar')) {

                try{

                    $request->uploadedAvatar = $this->upload($request);
                } catch (\Exception $e){
                    return $this->returnValidate($e->getMessage());

                }
            }
            //入库
            $data = ['content' => $user->updateRow($request)];
        }
        //返回修改后的记录数据
        return $this->returnArray($data);
    }

    /**
     * 上传头像
     * 需要创建软连接php artisan storage:link
     * @param mixed $request
     * @return mixed
     * @throws \Exception
     */
    public function upload (Request $request) {

        $file = $request->file('avatar');
        if ($file->isValid()) {
            // 获取文件相关信息
            // $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $allowExt = ['jpg','png','jpeg','gif'];
            //扩展限制
            if (!in_array($ext,$allowExt)){
                throw new \Exception('不允许上传此类文件');
            }
            // $realPath = $file->getRealPath();   //临时文件的绝对路径
            // $type = $file->getClientMimeType();     // image/jpeg
            //获取文件大小
            $size = $file->getClientSize();
            //大小限制5M
            if ($size > 5000000){
                throw new \Exception('上传文件过大');
            }

            // 上传文件
            $filename = time() . '-' . uniqid() . '.' . $ext;
            try {

                $path = $file->move('./storage/'.date('Ymd'),$filename);
            }catch (\Exception $fileException){
                throw new \Exception($fileException->getMessage());

            }

        }

        return $path;
    }

    /**
     * 获取用户收货地址
     *
     * @return mixed
     */
    public function getAddress (Request $request) {
        $request->id = isset($request->id) ? $request->id : $this->getSessionId();

        $address = new UserAddress();
        try {
            $info = $address->getAll($request)->map(function ($item) {
                return [
                    'id' => $item['id'],
                    'user_name' => $item['user_name'],
                    'province' => $item['province'],
                    'city' => $item['city'],
                    'area' => $item['area'],
                    'street' => $item['street'],
                    'phone' => $item['phone'],
                    'zip_code' => $item['zip_code'],
                    'is_default' => $item['is_default']
                ];

            });

        } catch (\Exception $e) {
            $info = [];
            \Log::info('获取用户地址接口getAddress返回：' . $e->getMessage());
        }
        return $this->returnArray($info);
    }
    /**
     * 添加收货地址
     *
     * @return mixed
     */
    public function addAddress (Request $request) {
        $validate = $this->validateRequest($request);
        if ($validate->fails()){
            $warnings = $validate->messages();
            return $this->returnValidate($warnings->first());
        }else{

            $address = new UserAddress();
            try {

                $info = ['content' => $address->insertRow($request)];

            } catch (\Exception $e) {
                //记录失败原因
                \Log::info('用户中心接口addAddress信息：'.$e->getMessage());
                return $this->returnArray('',500,'内部错误');
            }
        }
        return $this->returnArray($info);
    }
    /**
     * 编辑收货地址
     *
     * @return mixed
     */
    public function updateAddress (Request $request) {
        $validate = $this->validateRequest($request);
        if ($validate->fails()){
            $warnings = $validate->messages();
            return $this->returnValidate($warnings->first());
        } else {

            $address = new UserAddress();
            try {

                $info = ['content' => $address->updateRow($request)];

            } catch (\Exception $e) {

                \Log::info('用户中心接口updateAddress信息：'.$e->getMessage());
                return $this->returnArray('',500,'内部错误');
            }

        }
        return $this->returnArray($info);
    }

    /**
     * 删除收货地址
     *
     * @return mixed
     */
    public function delAddress (Request $request) {
        $address = new UserAddress();
        try {

            $info = ['content' => $address->deleteRow($request)];

        } catch (\Exception $e) {

            \Log::info('用户中心接口delAddress信息：'.$e->getMessage());
            return $this->returnArray('',500,'内部错误');
        }
        return $this->returnArray($info);
    }

    /**
     * 用户信息统计
     * @return mixed
     */
    public function getStatic (Request $request) {
        $userId = $this->getSessionId();
        //漏洞数量
        $vlusNum = Vuls::where(['user_id' => $userId])->count();
        //积分credit
        $user = Users::where(['id' => $userId])->first();
        $creditNum = $user->credit ? $user->credit : 0;
        //金币reward
        $rewardNum = $user->reward ? $user->reward : 0;
        //奖励order
        $orderNum = Order::where(['user_id' => $userId])->count();
        return $this->returnArray([
            'vlusNum' => $vlusNum,
            'creditNum' => $creditNum,
            'rewardNum' => $rewardNum,
            'orderNum' => $orderNum
        ]);
    }

    /**
     * 获取个人积分
     * @param mixed $request
     * @return mixed
     */
    public function getCredit (Request $request) {
        $data = [];
        $userId = $this->getSessionId();
        $per_page = isset($request->per_page) ? $request->per_page : 10;
        $page = isset($request->page) ? $request->page : 1;
        $where = ['user_id' => $userId, 'type' => RewardLog::CREDIT];
        $temp = RewardLog::getByWhere($where,['start'=>($page-1)*$per_page,'length'=>$per_page]);
        $data['count'] = RewardLog::getCount($where);
        $data['list'] = $temp->toArray();
        return $this->returnArray($data);
    }

    /**
     * 获取我的金币
     * @param mixed $request
     * @return mixed
     */
    public function getReward (Request $request) {
        $data = [];
        $userId = $this->getSessionId();
        $per_page = isset($request->per_page) ? $request->per_page : 10;
        $page = isset($request->page) ? $request->page : 1;
        $where = ['user_id' => $userId, 'type' => RewardLog::REWARD];
        $temp = RewardLog::getByWhere($where,['start'=>($page-1)*$per_page,'length'=>$per_page]);
        $data['count'] = RewardLog::getCount($where);
        $data['list'] = $temp->toArray();
        return $this->returnArray($data);
    }

    /**
     * 获取我的订单
     * @param mixed $request
     * @return mixed
     */
    public function getOrder (Request $request) {
        $data = [];
        $userId = $this->getSessionId();
        $order = new Order();
        $per_page = isset($request->per_page) ? $request->per_page : 10;
        $page = isset($request->page) ? $request->page : 1;
        $filed = ['orders.id','orders.sn', 'goods.name as goods_name', 'orders.consignee', 'orders.total', 'orders.status', 'orders.num', 'orders.created_at'];
        $where = ['user_id' => $userId];
        $join = ['table'=>'goods','relation'=>['goods.id' => 'orders.goods_id']];
        $limit = ['start'=>($page-1)*$per_page,'length'=>$per_page];
        $temp = $order->lists($filed,$where,$join,$limit);
        $data['count'] = $order->getCount($where);
        $data['list'] = $temp->toArray();
        return $this->returnArray($data);
    }

    /**
     * 获取一条收货地址
     * #支付成功后当前选择的那条地址
     * @param mixed $request
     * @return mixed
     */
    public function getAddressRow (Request $request){
        $address = new UserAddress();
        $info = [];
        try{
            $request->user_id = \Auth::user() ? \Auth::user()->id : 0;

            $info = $address->getRow($request);
        }catch (\Exception $e){
            \Log::info('getAddressRow接口错误消息：'. $e->getMessage());
        }
        return $this->returnArray($info);
    }

    /**
     * 验证request数据
     * @param mixed $request
     * @return mixed $validate
     */
    protected function validateRequest ($request) {
       $validate = Validator::make($request->all(), [
            'user_name' => ['required'],
            'province' => 'required',
            'city' => 'required',
            'area' => 'required',
            'street' => 'required',
            'phone' => 'required|digits_between:11,15'

        ],[
            'user_name.required' => '请填写收货人',
            'province.required' => '请填写省份',
            'city.required' => '请填写城市',
            'area.required' => '请填写区域',
            'street.required' => '请填写街道',
            'phone.required' => '请填写联系方式',
            'phone.digits_between' => '请填写正确的联系方式'
        ]);
       return $validate;
    }
    /**
     * 退出登陆
     */
    public function logout (){
        if (\Auth::user()) {
            //退出登陆
            \Auth::logout();
        }
        $data = ['content' => !\Auth::check()];
        return $this->returnArray($data);
    }
}
